package com.woniu.woniuk16.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.woniuk16.commens.ComUtil;
import com.woniu.woniuk16.dto.AccountSelRulesDto;
import com.woniu.woniuk16.dto.RuleDto;
import com.woniu.woniuk16.entity.WoniuAccountRule;
import com.woniu.woniuk16.entity.WoniuRule;
import com.woniu.woniuk16.mapper.WoniuAccountRuleMapper;
import com.woniu.woniuk16.param.AccountToRuleParam;
import com.woniu.woniuk16.service.WoniuAccountRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.woniuk16.service.WoniuRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiangle
 * @since 2021-12-17
 */
@Service
public class WoniuAccountRuleServiceImpl extends ServiceImpl<WoniuAccountRuleMapper, WoniuAccountRule> implements WoniuAccountRuleService {
    @Autowired
    private WoniuRuleService woniuRuleService;
    @Override
    public AccountSelRulesDto selById(Integer id) {
        QueryWrapper<WoniuAccountRule> warqw = new QueryWrapper<>();
        warqw.eq("account_id", id);
        List<WoniuAccountRule> list = list(warqw);
        List<Integer> ids = list.stream().map(WoniuAccountRule::getRuleId).collect(Collectors.toList());
        List<RuleDto> rules = woniuRuleService.getRules();

        AccountSelRulesDto accountSelRulesDto = new AccountSelRulesDto();

        accountSelRulesDto.setSelIds(ids);
        accountSelRulesDto.setRuleDtos(rules);
        return accountSelRulesDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changeRule(AccountToRuleParam accountToRuleParam) {
        QueryWrapper<WoniuAccountRule> arq = new QueryWrapper<>();
        arq.eq("account_id",accountToRuleParam.getAccountId());
        remove(arq);

        if (accountToRuleParam.getCheckList()==null||accountToRuleParam.getCheckList().size()<=0){
            return true;
        }
        List<Integer> checkList = accountToRuleParam.getCheckList();

        List<WoniuAccountRule> woniuAccountRules = new ArrayList<>();
        for (int i = 0; i < checkList.size(); i++) {
            woniuAccountRules.add(new WoniuAccountRule(null,accountToRuleParam.getAccountId(),checkList.get(i)));
        }

        saveBatch(woniuAccountRules);
        return true;
    }
}
